package com.xy.tool.webmvc.interceptor;

import com.xy.lang.util.NetUtils;
import com.xy.tool.context.UserContextHolder;
import org.slf4j.MDC;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogInterceptor extends HandlerInterceptorAdapter {

    private final static String KEY_APP_NAME = "appName";
    private final static String KEY_IP = "ip";
    private final static String KEY_USER_ID = "userId";
    private final static String KEY_USER_NAME = "userName";

    private String appName;

    public LogInterceptor(String appName) {
        this.appName = appName;
    }


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        MDC.put(KEY_APP_NAME, appName);
        MDC.put(KEY_IP, NetUtils.getHostAddress());
        MDC.put(KEY_USER_ID, String.valueOf(UserContextHolder.getUserId()));
        MDC.put(KEY_USER_NAME, UserContextHolder.getUserName());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                @Nullable Exception ex) throws Exception {
        MDC.remove(KEY_APP_NAME);
        MDC.remove(KEY_IP);
        MDC.remove(KEY_USER_ID);
        MDC.remove(KEY_USER_NAME);
    }

}
